package com.monkeyboy.service;

import com.monkeyboy.common.ParamData;
import com.monkeyboy.common.dto.LayuiData;
import com.monkeyboy.common.dto.ResData;
import com.monkeyboy.dao.BaseDao;
import com.monkeyboy.util.GetUUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Map;

/**
 * @Author Gavin
 * @date 2021.01.15 09:40
 */
@Service
public class UserService {
    @Autowired
    private BaseDao baseDao;

    public LayuiData getAllUsers(ParamData param) throws Exception {
        LayuiData res = new LayuiData();
        Map<String, Object> result = (Map<String, Object>) baseDao.findForPaging("UserMapper.getAllUser", param);
        if (result != null) {
            res.setCode(0);
            res.setData((ArrayList<Object>) result.get("data"));
            res.setCount(Integer.parseInt(String.valueOf(result.get("count"))));
            res.setMsg("");

        } else {
            res.setCode(0);
            res.setData(null);
            res.setCount(0);
            res.setMsg("暂无数据。");
        }

        return res;
    }

    @Transactional
    public ResData addUser(ParamData pd) throws Exception {
        if (StringUtils.isBlank(pd.getString("username"))) {
            return ResData.ERROR_500000("username不能为空。");
        }
        if (StringUtils.isBlank(pd.getString("phone"))) {
            return ResData.ERROR_500000("phone不能为空。");
        }
        if (baseDao.findForNum("UserMapper.findNumByUserName", pd.getString("username")) > 0) {
            return ResData.ERROR_500000("user_name已经存在。");
        }
        pd.put("user_id", GetUUID.getUUID());
        baseDao.save("UserMapper.insertOneUser", pd);
        return ResData.SUCCESS();
    }

    @Transactional
    public ResData delUser(String user_id) throws Exception {
        baseDao.delete("UserMapper.delUserById", user_id);
        return ResData.SUCCESS();
    }
}
